<template>
	<BasicModal @register="registerModalInner" :title="getTitle" @ok="handleSubmit">
		<BasicForm @register="registerForm"></BasicForm>
	</BasicModal>
</template>

<script setup lang="ts">
import { BasicModal, BasicForm } from '#/components';
import { useForm } from '#/hooks';
import { useModalInner } from '#/Modal';
import type { FormSchema } from '#/types';
import { addOrEditUser, getAllRoles } from '@/api/sys/account';
import { getDeptTree } from '@/api/sys/dept';
import { useMessage } from '@/hooks/web/useMessage';
import { computed, ref, unref } from 'vue';
import { isArray } from '@/utils/is';

const formSchema: FormSchema[] = [
	{
		field: 'username',
		label: '用户名',
		component: 'Input',
		required: true,
	},
	{
		field: 'name',
		label: '姓名',
		component: 'Input',
		required: true,
	},
	{
		field: 'roleId',
		label: '角色',
		component: 'ApiSelect',
		required: true,
		componentProps: {
			api: getAllRoles,
			labelField: 'roleName',
			valueField: 'roleId',
		},
	},
	{
		field: 'deptId',
		label: '部门',
		component: 'ApiTreeSelect',
		required: true,
		componentProps: {
			api: getDeptTree,
			fieldNames: { key: 'deptId', value: 'deptId', label: 'deptName' },
		},
	},
	{
		field: 'mobile',
		label: '电话',
		component: 'Input',
		rules: [{ len: 11, pattern: /^1[3456789]\d{9}$/, message: '请输入正确的电话号码', trigger: 'blur' }],
		componentProps: {
			maxLength: 11,
		},
	},
	{
		field: 'email',
		label: '邮箱',
		component: 'Input',
	},
];

const isUpdate = ref(true);
const userId = ref();

const { createMessage } = useMessage();

const [registerModalInner, { closeModal }] = useModalInner(data => {
	resetFields();
	isUpdate.value = !!data?.isUpdate;

	if (unref(isUpdate)) {
		userId.value = data.record.userId;
		setFieldsValue({ ...data.record });
	}
});

const [registerForm, { setFieldsValue, validate, resetFields }] = useForm({
	labelWidth: 70,
	schemas: formSchema,
	showActionButtonGroup: false,
	baseRowStyle: {
		'justify-content': 'space-around',
	},
	baseColProps: {
		span: 20,
	},
});

const getTitle = computed(() => (unref(isUpdate) ? '编辑人员' : '新增人员'));

const emit = defineEmits(['success', 'register']);
async function handleSubmit() {
	try {
		const values = await validate();
		if (unref(isUpdate)) {
			values.userId = userId.value;
		}

		if (!isArray(values.roleIdList)) {
			values.roleIdList = [values.roleId];
		}
		delete values.roleId;

		await addOrEditUser(isUpdate.value, values);
		closeModal();
		emit('success');
	} catch (_err) {
		createMessage.error('操作失败');
	}
}
</script>
<style lang="less" scoped></style>
